/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.myapp.struts;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

/**
 *
 * @author FAISAL
 */
public class FileCustom extends File{
    private String extension;
    private String name;

    public FileCustom(String path){
        super(path);
        if(this.isFile()){
            name = super.getName();
            extension = new String();
            int dotposition = name.lastIndexOf('.');
            if(dotposition != 0 && dotposition != -1){
                extension = name.substring(dotposition+1,name.length());
                name = name.substring(0,dotposition);
            }
        }
    }

    public String getExtension(){
        return extension;
    }
    
    @Override
    public String getName(){
        return name;
    }

    public String readFile() throws FileNotFoundException, IOException{
        if(getExtension().equals("txt")){
            Scanner scanner = new Scanner(this);
            String result = new String();
            while(scanner.hasNextLine()){
                if(result.isEmpty())
                    result = result + scanner.nextLine();
                else
                    result = result + " " + scanner.nextLine();
            }
            return result;
        }else if(getExtension().equals("doc")){
            String result = new String();
            FileInputStream fis = new FileInputStream(this.getAbsolutePath());
            HWPFDocument doc = new HWPFDocument(fis);
            WordExtractor extractor = new WordExtractor(doc);
            String[] Paragraphs = extractor.getParagraphText();
            if(Paragraphs != null){
                for(int i = 0; i < Paragraphs.length; i++){
                    if(result.isEmpty()){
                        result = result + Paragraphs[i].substring(0,Paragraphs[i].length()-1);
                    }else{
                        result = result + " " + Paragraphs[i].substring(0,Paragraphs[i].length()-1);
                    }
                }
            }
            return result;
        }else{
            return null;
        }
    }

    public static void runFile(String path) throws IOException{
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("cmd /c start " + path);
    }
}
